<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Cache-Control" content="no-siteapp">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=1, minimum-scale=1, maximum-scale=1">
<meta name="renderer" content="webkit">
<meta name="google" value="notranslate">
<meta name="robots" content="index,follow">


<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="足迹">
<meta name="twitter:description" content="走过就要留下点什么">
<meta name="twitter:image:src" content="http://wenjq.gitee.io/images/avatar.jpg">

<meta property="og:url" content="http://wenjq.gitee.io">
<meta property="og:title" content="足迹">
<meta property="og:description" content="走过就要留下点什么">
<meta property="og:site_name" content="足迹">
<meta property="og:image" content="http://wenjq.gitee.io/images/avatar.jpg">
<meta property="og:type" content="website">
<meta name="robots" content="noodp">

<meta itemprop="name" content="足迹">
<meta itemprop="description" content="走过就要留下点什么">
<meta itemprop="image" content="http://wenjq.gitee.io/images/avatar.jpg">

<link rel="canonical" href="http://wenjq.gitee.io">

<link rel="shortcut icon" href="/favicon.png">
<link rel="apple-itouch-icon" href="/favicon.png">
<link rel="stylesheet" href="/bundle/index.css">
<script type="text/javascript">
    var timeSinceLang = {
        year: '年前',
        month: '个月前',
        day: '天前',
        hour: '小时前',
        minute: '分钟前',
        second: '秒前'
    };
    var root = '';
</script>


        <meta name="keywords" content="dotnet core,vue.js,">
        <meta name="description" content=".net core &#43; vue开发单页应用（一）">
        <meta name="author" content="">
        <title>.net core &#43; vue开发单页应用（一）</title>
    </head>
    <body>
        <article class="container">
            <header class="header-wrap">
  <a class="index" href="/">
    <img class="logo" src="/images/avatar.jpg" />
    足迹
  </a>
  <ul class="menu">
      <li class="menu-item"><a href="/archive.html">归档</a></li>
      <li class="menu-item"><a href="/tag.html">标签</a></li>
      <li class="menu-item"><a href="/atom.xml">订阅</a></li>
  </ul>
</header>

            <article class="main article">
                <h1 class="title">.net core &#43; vue开发单页应用（一）</h1>
                <section class="info">
                    
                    
                    
                    <span class="date" data-time="1495764242"><span class="from"></span></span>
                    
                    <span class="tags"><a class="tag" href="/tag/dotnet%20core/index.html">dotnet core</a><a class="tag" href="/tag/vue.js/index.html">vue.js</a></span>
                </section>
                <article class="content"><h1>背景</h1>

<p>.net core 与 vue 的简介不再赘述，目前使用vue开发基本分为几种情况：</p>

<ul>
<li>使用webpack进行纯前端开发</li>
<li>传统的web应用中使用vue，主要使用vue的对象模型绑定</li>
</ul>

<hr />

<p>对于使用传统的web+vue进行单页面应用开的几乎没有找到例子，因此决定自己动手尝试，让自己在实际的应用中学习vue，并将自己的学习过程记录下来。个人认为，这种开发方式更适用于此类的猿：</p>

<ul>
<li>不会使用Node开发，希望使用传统的发布方式进行发布。</li>
<li>为了更爽，希望使用angular、vue等前端框架。</li>
<li>尝试单页应用的开发，如果是传统的web应用，使用vue的例子、教程就很多了。</li>
</ul>

<h1>依赖的环境和开发工具</h1>

<ul>
<li>vs2017（当然也可以是vs2015）</li>
<li>NPM Task Runner(vs插件，用来在vs中执行npm命令，当然也可以在cmd中直接使用,可以在<a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.NPMTaskRunner下载">https://marketplace.visualstudio.com/items?itemName=MadsKristensen.NPMTaskRunner下载</a>)</li>
<li>Node环境（webpack依赖Node环境，开发完的应用部署不依赖Node）</li>
</ul>

<h1>使用到的技术</h1>

<ul>
<li>.net core</li>
<li>vue</li>
<li>element ui</li>
</ul>

<h1>先创建一个项目吧</h1>

<h2>创建应用</h2>

<p>打开vs创建一个.net mvc应用
<img src="" data-src="/images/20180530144550999.png" alt="" />
选择web应用
<img src="" data-src="/images/20180530144606503.png" alt="" />
等待创建完成后，调整目录，删除不必要模板、css引用等。控制器中只保留一个Index。视图只保留Home/Index。
<img src="" data-src="/images/20180530144622156.png" alt="" />
<img src="" data-src="/images/20180530144628262.png" alt="" />
最后目录结构如下：
<img src="" data-src="/images/20180530144641378.png" alt="" /></p>

<h2>使用webpack</h2>

<p>为工程创建webpack、vue配置文件
<img src="" data-src="/images/20180530144655995.png" alt="" />
配置内容如下：</p>

<p>app.conf.js</p>

<pre><code class="language-javascript">    exports.conf = {
        dev: true,//开发模式
        assetsSubDirectory:'resources'//资源目录
    }
</code></pre>

<p>utils.js</p>

<pre><code class="language-javascript">  var path = require('path')
  var conf = require('./app.conf')
  var ExtractTextPlugin = require('extract-text-webpack-plugin')

  exports.assetsPath = function (_path) {
      return path.posix.join(conf.conf.assetsSubDirectory, _path)
  }

  exports.cssLoaders = function (options) {
    options = options || {}

    var cssLoader = {
      loader: 'css-loader',
      options: {
          minimize: !conf.conf.dev,
        sourceMap: options.sourceMap
      }
    }

    // generate loader string to be used with extract text plugin
    function generateLoaders (loader, loaderOptions) {
      var loaders = [cssLoader]
      if (loader) {
        loaders.push({
          loader: loader + '-loader',
          options: Object.assign({}, loaderOptions, {
            sourceMap: options.sourceMap
          })
        })
      }

      // Extract CSS when that option is specified
      // (which is the case during production build)
      if (options.extract) {
        return ExtractTextPlugin.extract({
          use: loaders,
          fallback: 'vue-style-loader'
        })
      } else {
        return ['vue-style-loader'].concat(loaders)
      }
    }

    // https://vue-loader.vuejs.org/en/configurations/extract-css.html
    return {
      css: generateLoaders(),
      postcss: generateLoaders(),
      less: generateLoaders('less'),
      sass: generateLoaders('sass', { indentedSyntax: true }),
      scss: generateLoaders('sass'),
      stylus: generateLoaders('stylus'),
      styl: generateLoaders('stylus')
    }
  }

  // Generate loaders for standalone style files (outside of .vue)
  exports.styleLoaders = function (options) {
    var output = []
    var loaders = exports.cssLoaders(options)
    for (var extension in loaders) {
      var loader = loaders[extension]
      output.push({
        test: new RegExp('\\.' + extension + '$'),
        use: loader
      })
    }
    return output
  }
</code></pre>

<p>vue-loader.conf.js</p>

<pre><code class="language-javascript">  var utils = require('./utils')
  var conf = require('./app.conf')
  module.exports = {
      loaders: utils.cssLoaders({
          sourceMap: !conf.conf.dev,
          extract: conf.conf.dev
      })
  }
</code></pre>

<p>webpack.config.js</p>

<pre><code class="language-javascript">var path = require('path')
  var utils = require('./utils')
  var webpack = require('webpack')
  var conf = require('./app.conf')
  function resolve(dir) {
      return path.join(__dirname, dir)
  }
  module.exports = {
      entry: {
          app: './wwwroot/main.js'
      },
      output: {
          filename: 'bundle.js',
          path: path.resolve(__dirname, './wwwroot/dist/')
      },
      module: {
          rules: [
              {
                  test: /\.vue$/,
                  loader: 'vue-loader'
              },
              {
                  test: /\.js$/,
                  loader: 'babel-loader',
                  include: [resolve('wwwroot')]
              },
              {
                  test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                  loader: 'url-loader',
                  options: {
                      limit: 10000,
                      name: utils.assetsPath('img/[name].[hash:7].[ext]'),
                      options: {
                          publicPath: 'dist/resources/img/'
                      }
                  }
              },
              {
                  test: /\.css$/,
                  loader: 'style-loader!css-loader'
              },
              {
                  test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
                  loader: 'file-loader',
                  options: {
                      publicPath: 'dist/'
                  }
              },
          ]
      },
      resolve: {
          extensions: ['.js', '.vue', '.json'],
      }
  };
</code></pre>

<p>进入项目的主目录（Startup.cs所在的目录），执行npm命令：</p>

<pre><code class="language-shell">  npm init -y
  npm install
</code></pre>

<p>wwwroot下创建main.js,目前先测试项目结构是否正常，不引入路由等插件。</p>

<pre><code class="language-javascript">    import Vue from 'vue'
    import App from './App'
    new Vue({
        render: h =&gt; h(App)
    }).$mount('#app')
</code></pre>

<p>wwwroot下创建App.vue文件,只简单显示一个字符串</p>

<pre><code class="language-vue">    &lt;template&gt;
    &lt;div id=&quot;app&quot;&gt;
        {{msg}}
    &lt;/div&gt;
    &lt;/template&gt;
    &lt;script&gt;
    export default {
        name: 'app',
            components: {
            },
            data() {
                return {
                    msg:'Hello Vue'
                }
            }
        }
    &lt;/script&gt;
</code></pre>

<h1>编译项目，运行起来吧</h1>

<p>可以先在cmd中运行</p>

<pre><code>  npm run build
</code></pre>

<p>验证配置无错后运行。也可以直接编译，NPM Task Runner插件会在vs编译时同时运行npm命令。
<img src="" data-src="/images/20180530145729379.png" alt="" />
已经可以正常运行了，下一篇将开始进行正式的应用开发流程。</p>
</article>
                <section class="author">
                    
                    <a class="name" href="/about..html"></a>
                    <div class="intro"></div>
                </section>
                <section class="recommend">
                    
                    <section class="nav prev more">
                        <div class="head">上篇文章</div>
                        <a class="link" href="/20180527.html">saiku3.15整合（非maven）</a>
                    </section>
                    
                    
                    <section class="nav next more">
                        <div class="head">下篇文章</div>
                        <a class="link" href="/2018053001.html">Maven的使用</a>
                    </section>
                    
                </section>
                

            </article>
        </article>
        <footer class="footer">
    <span class="copyright">
        足迹 ©
        <script type="text/javascript">
            document.write(new Date().getFullYear());
        </script>
    </span>
    <span class="publish">Powered by <a href="http://www.chole.io/" target="_blank">Ink</a></span>
</footer>

        <script src="/bundle/index.js"></script>
    </body>
</html>
